import { useDebounceFn, useEventListener } from '@vueuse/core'
import {
	DragEvent,
	Image,
	ImageEvent,
	Leafer,
	Pen,
	ZoomEvent,
	LeafHelper,
	RotateEvent,
	ImageManager,
	ResizeEvent
} from 'leafer-ui'
import '@leafer-in/viewport'
import '@leafer-in/view'
import '@leafer-in/animate'
import useHistoryUtil from './useHistoryUtil'
import { nextTick, onMounted, ref, watch } from 'vue'

const zoomConfig = {
	step: 0.2,
	min: 0.2,
	max: 5,
	padding: 10
}

export const useMark = (config: { id: string }) => {
	let app: Leafer
	let isDrawing = false
	let pen: Pen
	let bgImage: Image
	const scale = ref(1)
	const color = ref('#C40833')
	const startPen = ref(false)
	let fitScale = 1
	const loading = ref(false)
	const penWidth = ref(10 || 2)

	const historyUtil = useHistoryUtil((v: any) => {
		pen.set(v)
	})
	const startDrawing = (e: DragEvent) => {
		if (e?.multiTouch) return (isDrawing = false)
		if (startPen.value) {
			isDrawing = true
			const point = e.getPagePoint()
			pen.setStyle({
				stroke: color.value,
				strokeWidth: penWidth.value / fitScale, //保证不同大小的图片画笔宽度显示一致
				strokeCap: 'round',
				strokeJoin: 'round',
				// blendMode:'xor',
				eraser: true
			})
			pen.moveTo(point.x, point.y)
		}
	}

	const continueDrawing = (e: DragEvent) => {
    console.log("e",e)
		if (e?.multiTouch) return (isDrawing = false)
		if (isDrawing && startPen.value) {
			const point = e.getPagePoint()
			pen.lineTo(point.x, point.y)
		}
	}

	const stopDrawing = (e: DragEvent) => {
		if (isDrawing && startPen.value) {
			isDrawing = false
			app.off(DragEvent.DRAG, dragDragHandler)
			app.off(DragEvent.END, stopDrawing)
			historyUtil.commit(pen.toJSON())
		}
	}

	const dragDragHandler = (e: DragEvent) => {
		continueDrawing(e)
	}
	const initPen = (data: string | undefined | null) => {
		if (pen) {
			app.remove(pen)
		}
		pen = new Pen()
		app.add(pen)
		const penData = data
		console.log('penData', typeof penData)
		if (!!penData) {
			const data = JSON.parse(penData)
			pen.set(data)
			historyUtil.init(data)
		} else {
			historyUtil.init(pen.toJSON())
		}
	}
	const initImg = async (data: {
		url: string
		penData: string | undefined | null
	}) => {
		loading.value = true
		return new Promise<void>((resolve, reject) => {
			if (bgImage) {
				app.remove(bgImage)
				app.remove(pen)
			}
			bgImage = new Image({
				url: data.url,
				pixelRatio: 3
			})
			app.add(bgImage)
			bgImage.once(ImageEvent.LOADED, async () => {
				await nextTick()
				app.zoom('fit', zoomConfig.padding)
				scale.value = 1
				fitScale = +app.scale
				app.config.zoom = {
					min: zoomConfig.min * fitScale,
					max: zoomConfig.max * fitScale
				}
				initPen(data.penData)
				loading.value = false
				resolve()
			})
		})
	}
	const init = () => {
		app = new Leafer({
			view: config.id,
			smooth: true,
			pointer: { touch: true },
			touch: { preventDefault: true },
			type: 'design',
			move: {
				scroll: false,
				//拖拽，
				drag: true
			},
			usePartRender: false
		})
		app.on(ZoomEvent.ZOOM, function () {
			scale.value = +app.scale / fitScale
		})
		app.on(DragEvent.START, (e: DragEvent) => {
			if (startPen.value) {
				startDrawing(e)
				app.on(DragEvent.DRAG, dragDragHandler)
				app.on(DragEvent.END, stopDrawing)
			}
		})
		//双指旋转
		app.on(RotateEvent.ROTATE, function (e: RotateEvent) {
			const center = { x: e.x, y: e.y }
			LeafHelper.rotateOfWorld(app, center, e.rotation)
		})
		//监听画布大小改变
		app.on(ResizeEvent.RESIZE, () => {
			hanResize()
		})
		// initImg()
	}

	const clear = () => {
		pen.clear()
		historyUtil.commit(pen.toJSON())
	}
	const hanRotate = (isLeft: boolean) => {
		app.rotateOf('center', isLeft ? -90 : 90)
	}
	const hanScale = (isAdd: boolean) => {
		const step = zoomConfig.step
		let newScale = scale.value + (isAdd ? step : -step)
		if (newScale < zoomConfig.min) newScale = zoomConfig.min
		if (newScale > zoomConfig.max) newScale = zoomConfig.max
		scale.value = newScale
		const target = newScale * fitScale
		app.zoom(target, zoomConfig.padding, false, 0.2)
	}
	const hanResize = useDebounceFn(() => {
		if (!app.ready) return
		app.zoom(bgImage, zoomConfig.padding, !true, 0.2)
		scale.value = 1
	}, 300)
	watch(
		() => startPen.value,
		() => {
			app.config.move = {
				...(app.config.move || {}),
				drag: !startPen.value
			}
		}
	)
	onMounted(() => {
		init()
	})
	useEventListener('unload', () => {
		const { list } = Leafer
		list.forEach((leafer) => (leafer as Leafer).destroy(true))
		list.destroy()
		ImageManager.destroy()
	})
	const destroy = () => {
		app.destroy()
	}
	return {
		hanScale,
		hanResize,
		hanRotate,
		clear,
		historyUtil,
		scale,
		startPen,
		color,
		initImg,
		destroy,
		loading,
		penWidth
	}
}
